package com.JFapp.service.impl;

import com.JFapp.domain.entity.LoginUser;
import com.JFapp.domain.entity.ResponseResult;
import com.JFapp.domain.entity.User;
import com.JFapp.domain.vo.UserInfoVo;
import com.JFapp.domain.vo.UserLoginVo;
import com.JFapp.eumns.AppHttpCodeEnum;
import com.JFapp.service.LoginService;
import com.JFapp.service.MailService;
import com.JFapp.service.UserService;
import com.JFapp.utils.BeanCopyUtils;
import com.JFapp.utils.JwtUtil;
import com.JFapp.utils.RedisCache;
import com.JFapp.utils.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserService userService;
    @Override
    public ResponseResult login(User user) {

        //AuthenticationToken使用UserDetailService默认调用内存查询，需要重写到表查询；
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //认证判断
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //根据id生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //强转为String
        String id = loginUser.getUser().getId().toString();
        String jwt= JwtUtil.createJWT(id);

        //用户信息存入redis
        redisCache.setCacheObject("JFapp:"+id,loginUser);

        //封装token以及user(user->userInfoVo)
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        UserLoginVo vo =new UserLoginVo(jwt,userInfoVo);
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult logout() {
        //从token中获取id
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long id = loginUser.getUser().getId();
        redisCache.deleteObject("JFapp:"+id);
        return ResponseResult.okResult();
    }


    private static final Long timeMillis = 5*60*1000L;

    @Autowired
    private MailService mailService;
    @Override
    @ApiOperation("发送重置邮件")
    public ResponseResult resetPassword(User user) {
        //生成token
        String token = JwtUtil.createJWT(user.getUserName(), timeMillis);
        mailService.sendEmail("ResetPassword",token,user.getEmail());
        return ResponseResult.okResult(token);
    }

    @Override
    @ApiOperation("重置密码")
    public ResponseResult changePassword(String password, String token) {
        String userName;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userName = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException(AppHttpCodeEnum.OUT_OF_TOKEN);
        }

        String newPassword = passwordEncoder.encode(password);
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userService.update(lambdaUpdateWrapper
                .set(User::getPassword, newPassword)
                .eq(User::getUserName, userName));

        return ResponseResult.okResult();
    }


}
